<template>
  <div class="editor-wrap">
    <h1 class="editor-title"><span class="gradient-text">添加宣传模块</span></h1>

    <!-- ① 工厂：选类型 + 添加 -->
    <div class="factory-bar">
      <el-radio-group v-model="factoryType" size="medium">
        <el-radio-button label="mixed">图文</el-radio-button>
        <el-radio-button label="image">图集</el-radio-button>
        <el-radio-button label="video">视频集</el-radio-button>
      </el-radio-group>
      <el-button type="primary" size="medium" icon="el-icon-plus" @click="addModule">
        添加模块
      </el-button>
    </div>

    <!-- ② 模块列表（拖拽排序） -->
    <draggable 
      v-model="modules" 
      handle=".drag-handle"
      @end="onDragEnd"
    >
      <transition-group>
        <div
          v-for="(mod, idx) in modules"
          :key="mod.id"
          class="editor-module-card"
        >
          <i class="el-icon-rank drag-handle" />
          <div class="editor-mod-header">
            <span class="editor-mod-type">{{ typeLabel(mod.type) }}</span>
            <div class="order-info">
              <span class="order-label">顺序值:</span>
              <el-input-number
                v-model="mod.orderIndex"
                :min="0"
                size="mini"
                style="width: 90px"
              />
            </div>
            <el-button
              type="text"
              icon="el-icon-delete"
              @click="modules.splice(idx, 1)"
            />
          </div>

          <!-- 图文 -->
          <template v-if="mod.type === 'mixed'">
            <div
              v-for="(item, i) in mod.list"
              :key="i"
              class="editor-mixed-card"
            >
              <!-- 删除按钮放在卡片右上角 -->
              <i class="el-icon-delete editor-del-mixed" @click="mod.list.splice(i, 1)" />
              
              <div class="editor-mixed-content">
                <div class="editor-mixed-left">
                  <el-upload
                    class="editor-mixed-uploader"
                    action="/api/api/upload"
                    name="files"
                    :show-file-list="false"
                    :on-success="(res)=>item.img = res.data[0]"
                  >
                    <img v-if="item.img" :src="item.img" class="editor-mixed-img" />
                    <div v-else class="editor-mixed-placeholder">
                      <i class="el-icon-plus" />
                      <span>上传图片</span>
                    </div>
                  </el-upload>
                </div>

                <div class="editor-mixed-right">
                  <el-input
                    v-model="item.txt"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入配图文字..."
                    class="editor-mixed-input"
                    maxlength="200"
                    show-word-limit
                  />
                </div>
              </div>
            </div>
            <el-button
              type="dashed"
              size="mini"
              icon="el-icon-plus"
              class="editor-add-more"
              @click="mod.list.push({ img: '', txt: '' })"
            >
              再加一条图文
            </el-button>
          </template>

          <!-- 图集 -->
          <template v-if="mod.type === 'image'">
            <el-upload
              multiple
              action="/api/api/upload"
              name="files"
              list-type="picture-card"
              :file-list="mod.list"
              :on-success="handleImageSuccess"
              :on-remove="handleImageRemove"
            >
              <i class="el-icon-plus" />
            </el-upload>
            <!-- 显示逗号分隔的URL字符串 -->
            <div class="url-preview" v-if="mod.list && mod.list.length > 0">
              <el-tag type="info">URL列表: {{ getImageUrls(mod.list) }}</el-tag>
            </div>
          </template>

          <!-- 视频集 -->
          <template v-if="mod.type === 'video'">
            <el-upload
              multiple
              action="/api/api/upload"
              name="files"
              :file-list="mod.list"
              :on-success="handleVideoSuccess"
              :on-remove="handleVideoRemove"
              :before-upload="beforeVideo"
            >
              <el-button size="small" type="primary">选择视频</el-button>
            </el-upload>
            <!-- 显示逗号分隔的URL字符串 -->
            <div class="url-preview" v-if="mod.list && mod.list.length > 0">
              <el-tag type="info">URL列表: {{ getVideoUrls(mod.list) }}</el-tag>
            </div>
          </template>
        </div>
      </transition-group>
    </draggable>

    <!-- ③ 统一保存 -->
    <el-button type="primary" class="editor-save-btn" @click="submit">
      保存全部模块
    </el-button>
  </div>
</template>

<script>
import { batchItem } from '@/api/index'
import draggable from 'vuedraggable'

export default {
  name: 'ItemEditor',
  components: { draggable },
  props: { configId: { type: Number, required: true } },
  data() {
    return {
      factoryType: 'mixed',
      modules: []
    }
  },
  methods: {
    beforeVideo(file) {
      const isVideo = file.type.startsWith('video/')
      if (!isVideo) this.$message.error('只能上传视频')
      return isVideo
    },
    
    // 图片上传成功处理
    handleImageSuccess(res, file) {
      const url = res.data[0]
      // 找到当前模块
      const currentModule = this.modules.find(mod => mod.type === 'image')
      if (currentModule) {
        if (!currentModule.list) {
          currentModule.list = []
        }
        currentModule.list.push({ url: url })
      }
    },
    
    // 图片删除处理
    handleImageRemove(file, fileList) {
      const currentModule = this.modules.find(mod => mod.type === 'image')
      if (currentModule) {
        currentModule.list = fileList
      }
    },
    
    // 视频上传成功处理
    handleVideoSuccess(res, file) {
      const url = res.data[0]
      // 找到当前模块
      const currentModule = this.modules.find(mod => mod.type === 'video')
      if (currentModule) {
        if (!currentModule.list) {
          currentModule.list = []
        }
        currentModule.list.push({ url: url })
      }
    },
    
    // 视频删除处理
    handleVideoRemove(file, fileList) {
      const currentModule = this.modules.find(mod => mod.type === 'video')
      if (currentModule) {
        currentModule.list = fileList
      }
    },
    
    // 获取图片URL的逗号分隔字符串
    getImageUrls(list) {
      return list.map(item => item.url).join(',')
    },
    
    // 获取视频URL的逗号分隔字符串
    getVideoUrls(list) {
      return list.map(item => item.url).join(',')
    },
    
    addModule() {
      const base = {
        id: Date.now(),
        type: this.factoryType,
        orderIndex: this.modules.length * 10,
        list: []
      }
      if (base.type === 'mixed') base.list.push({ img: '', txt: '' })
      this.modules.push(base)
    },
    
    typeLabel(t) {
      return { mixed: '图文', image: '图集', video: '视频集' }[t]
    },
    
    // 拖拽结束事件处理
    onDragEnd() {
      // 重新计算所有模块的顺序值
      this.modules.forEach((module, index) => {
        module.orderIndex = index * 10;
      });
    },
    
    async submit() {
      if (this.modules.length === 0) {
        this.$message.warning('请先添加模块')
        return
      }
      
      // 按照后端预览页面期望的数据结构封装
      const dto = {
        pageConfigId: this.configId,
        modules: this.modules.map(m => {
          // 按照第一个上传的图文结构
          if (m.type === 'mixed') {
            // 图文类型：直接存储 list 数组
            return {
              type: this.mapTypeToContentType(m.type),
              orderIndex: m.orderIndex,
              content: JSON.stringify(m.list), // 存储图文列表
              list: null
            }
          } else if (m.type === 'image') {
            // 图片类型：content 为空，list 存储逗号分隔的URL字符串
            const urlString = m.list.map(it => it.url).join(',')
            return {
              type: this.mapTypeToContentType(m.type),
              orderIndex: m.orderIndex,
              content: '',
              list: urlString  // 改为字符串
            }
          } else if (m.type === 'video') {
            // 视频类型：content 为空，list 存储逗号分隔的URL字符串
            const urlString = m.list.map(it => it.url).join(',')
            return {
              type: this.mapTypeToContentType(m.type),
              orderIndex: m.orderIndex,
              content: '',
              list: urlString  // 改为字符串
            }
          }
        })
      }
      
      console.log('提交的数据:', JSON.stringify(dto, null, 2));
      await batchItem(dto)
      this.$message.success('已全部保存')
      this.$emit('saved')
    },
    
    // 添加类型映射方法
    mapTypeToContentType(type) {
      const typeMap = {
        'mixed': 'MIXED',
        'image': 'IMAGE', 
        'video': 'VIDEO'
      };
      return typeMap[type] || 'MIXED';
    }
  }
}
</script>


<style scoped>
/* ---------- 整体 ---------- */
.editor-wrap {
  padding: 24px;
  background: #f5f6f7;
  min-height: 100vh;
}
.editor-title {
  font-size: 28px;
  font-weight: 600;
  text-align: center;
  margin-bottom: 32px;
  letter-spacing: 1px;
}
.gradient-text {
  background: linear-gradient(135deg, #004c70 0%, #d4a574 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

/* 工厂栏 */
.factory-bar {
  display: flex;
  gap: 12px;
  justify-content: center;
  margin-bottom: 24px;
}

/* 模块卡片 */
.editor-module-card {
  background: #fff;
  border-radius: 20px;
  padding: 20px 24px;
  margin-bottom: 16px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
  transition: all 0.3s;
  position: relative;
}
.editor-module-card:hover {
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.1);
}
.editor-mod-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}
.editor-mod-type {
  font-weight: 600;
  color: #004c70;
  flex: 1;
}
.order-info {
  display: flex;
  align-items: center;
  gap: 8px;
}
.order-label {
  font-size: 12px;
  color: #909399;
}
.drag-handle {
  cursor: move;
  color: #999;
  font-size: 18px;
  position: absolute;
  top: 16px;
  left: 16px;
  z-index: 1;
  padding: 4px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 4px;
  transition: all 0.3s;
}
.drag-handle:hover {
  background: #f0f0f0;
  color: #004c70;
}

/* 图文子项 - 重新设计的布局 */
.editor-mixed-card {
  position: relative;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  background: #fafafa;
  transition: all 0.3s;
}
.editor-mixed-card:hover {
  border-color: #c0c4cc;
  background: #f5f7fa;
}

.editor-mixed-content {
  display: flex;
  gap: 16px;
  align-items: flex-start;
}

/* 图片上传区域 */
.editor-mixed-left {
  flex-shrink: 0;
}
.editor-mixed-uploader {
  width: 120px;
  height: 120px;
  border: 1px dashed #dcdfe6;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  cursor: pointer;
  transition: border-color 0.3s;
}
.editor-mixed-uploader:hover {
  border-color: #409eff;
}
.editor-mixed-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}
.editor-mixed-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 14px;
}
.editor-mixed-placeholder i {
  font-size: 24px;
  margin-bottom: 8px;
}

/* 文本输入区域 */
.editor-mixed-right {
  flex: 1;
  min-width: 0; /* 防止flex元素溢出 */
}
.editor-mixed-input {
  width: 100%;
}

/* 删除按钮位置 */
.editor-del-mixed {
  position: absolute;
  top: 12px;
  right: 12px;
  cursor: pointer;
  color: #f56c6c;
  font-size: 18px;
  padding: 4px;
  background: #fff;
  border-radius: 50%;
  transition: all 0.3s;
  z-index: 1;
}
.editor-del-mixed:hover {
  background: #fef0f0;
  transform: scale(1.1);
}

/* 再加一条按钮 */
.editor-add-more {
  width: 100%;
  margin-top: 8px;
}

/* 保存按钮 */
.editor-save-btn {
  margin-top: 28px;
  width: 100%;
  height: 46px;
  border-radius: 24px;
  font-size: 16px;
  letter-spacing: 2px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .editor-mixed-content {
    flex-direction: column;
  }
  
  .editor-mixed-left {
    align-self: center;
  }
  
  .editor-mixed-uploader {
    width: 150px;
    height: 150px;
  }
  
  .editor-mod-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .order-info {
    align-self: flex-end;
  }
}

.url-preview {
  margin-top: 10px;
  padding: 8px;
  background: #f5f7fa;
  border-radius: 4px;
}

.url-preview .el-tag {
  white-space: normal;
  word-break: break-all;
  max-width: 100%;
}

/* 拖拽过渡效果 */
.sortable-ghost {
  opacity: 0.5;
  background: #c8ebfb;
}

.sortable-chosen {
  box-shadow: 0 8px 30px rgba(0, 76, 112, 0.2);
}
</style>